package com.gitee.dynamicproxy.cglib;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author ming.yan-1
 * @version V1.0
 * @Title com.gitee.dynamicproxy.cglib
 * @Description
 * @date 2018/9/11  下午7:49
 */
public class CglibDemo {

    private Object object;

    public Object instance(Object object){
        this.object = object;
        Enhancer enhancer = new Enhancer();
        //设置父类
        enhancer.setSuperclass(object.getClass());
        //设置方法拦截器
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("cglib 增强前");
                //调用到生成的代理类的方法,传参为o，代理类的实例
                Object result = methodProxy.invokeSuper(o,objects);
                //调用实际的类的方法，传参为object，为实际的类的实例
                //Object result = methodProxy.invoke(object,objects);
                //反射到实体类的方法
                //Object result = method.invoke(object,objects);
                System.out.println("cglib 增强后");
                return result;
            }
        });
        return enhancer.create();
    }

}
